<?php

namespace App\Console\Commands\Controller;

use App\Common\Libs\ArrayHelper;
use App\Console\BaseCommand;
use App\Consts\GlobalLoginConst;
use App\Models\Cache\Cache;
use App\Models\Cache\CacheKey;
use App\Models\LogLogin;
use App\Models\Tourist;
use Illuminate\Support\Facades\DB;

class LogLoginCommand extends BaseCommand
{
    protected $signature = 'controller:log-login {action} {json}';

    protected $description = 'log login commands';

    public function add($loadData)
    {
        $loginTime = time();

        // 更新用户最后登录时间
        $user = repository()->UserRepository->getUserByUserId($loadData['user_id']);
        if ($user) {
            repository()->UserRepository->updateUser($user, [
                'last_login_at' => $loginTime,
            ]);
        }

        // 新增[tourist]表记录
        if ($loadData['access_token']) {
            $touristId = Cache::getInstance([
                'token' => $loadData['access_token'],
            ])->get(CacheKey::TOKEN_TOURIST_SNAPSHOT);
            if ($touristId) {
                $query = Tourist::getInstance()
                    ->where('tourist_id', $touristId)
                    ->where('user_id', $loadData['user_id']);
                if (empty($query->first())) {
                    $query->create([
                        'tourist_id' => $touristId,
                        'user_id' => $loadData['user_id'],
                        'platform' => GlobalLoginConst::LOGIN_PLATFORM_WEB,
                        'device_id' => GlobalLoginConst::LOGIN_PLATFORM_WEB_STR . '_' . $touristId,
                    ]);
                }
            }
        }

        // 记录登录日志
        unset($loadData['access_token']);
        $tableName = LogLogin::getTableNameBySeason($loginTime);
        $this->createTable($tableName);
        LogLogin::setTableName($tableName)->create($loadData);

        return true;
    }

    /**
     * @param $tableName
     * @return bool
     */
    public function createTable($tableName)
    {
        $tables = DB::select('SHOW TABLES');
        $tables = ArrayHelper::getColumn($tables, 'Tables_in_' . env('DB_DATABASE'));

        if (!in_array($tableName, $tables)) {
            DB::select('CREATE TABLE IF NOT EXISTS `' . $tableName . '` (LIKE `syslog_tourist_202011`);');
        }

        return true;
    }

}
